<template>
  <div class="main">
    <div class="flex justify-between items-center mb-4">
      <h2 class="text-xl font-bold">机构管理</h2>
      <div class="flex space-x-2">
        <el-button
          type="danger"
          :disabled="selectedOrganizations.length === 0"
          @click="handleBatchDelete"
        >
          批量删除
        </el-button>
        <el-button type="primary" @click="handleAdd">新增机构</el-button>
      </div>
    </div>

    <!-- 搜索区域 -->
    <div class="bg-white p-4 rounded-lg shadow mb-4">
      <el-form :inline="true" :model="searchForm" class="demo-form-inline">
        <el-form-item label="机构编号">
          <el-input
            v-model="searchForm.posNumber"
            placeholder="请输入机构编号"
            clearable
          />
        </el-form-item>
        <el-form-item>
          <el-button type="primary" @click="handleSearch">搜索</el-button>
          <el-button @click="resetSearch">重置</el-button>
        </el-form-item>
      </el-form>
    </div>

    <!-- 表格区域 -->
    <div class="bg-white rounded-lg shadow">
      <el-table
        :data="organizationTree"
        row-key="id"
        :tree-props="{ children: 'children', hasChildren: 'hasChildren' }"
        border
        @selection-change="handleSelectionChange"
      >
        <el-table-column type="selection" width="55" />
        <el-table-column prop="posNumber" label="机构编号" />
        <el-table-column prop="name" label="机构名称">
          <template #default="{ row }">
            {{ row.level === 0 ? row.cellName : row.name }}
          </template>
        </el-table-column>
        <el-table-column prop="level" label="层级">
          <template #default="{ row }">
            <el-tag v-if="row.level === 0" type="success">一级</el-tag>
            <el-tag v-else-if="row.level === 1" type="warning">二级</el-tag>
            <el-tag v-else type="info">{{ row.level }}级</el-tag>
          </template>
        </el-table-column>
        <el-table-column prop="type" label="类型">
          <template #default="{ row }">
            <el-tag v-if="row.type === 0" type="success">机构</el-tag>
            <el-tag v-else-if="row.type === 1" type="warning">部门</el-tag>
            <el-tag v-else type="info">岗位</el-tag>
          </template>
        </el-table-column>
        <el-table-column prop="ordered" label="排序" />
        <el-table-column prop="createTime" label="创建时间" />
        <el-table-column label="操作" width="220" fixed="right">
          <template #default="{ row }">
            <div class="operation-buttons">
              <el-tooltip content="编辑" placement="top" :hide-after="0">
                <el-button
                  type="primary"
                  size="small"
                  :icon="Edit"
                  circle
                  @click="handleEdit(row)"
                />
              </el-tooltip>

              <el-tooltip content="删除" placement="top" :hide-after="0">
                <el-popconfirm
                  title="确定删除该机构吗？"
                  confirm-button-text="确定"
                  cancel-button-text="取消"
                  @confirm="handleDelete(row)"
                >
                  <template #reference>
                    <el-button
                      type="danger"
                      size="small"
                      :icon="Delete"
                      circle
                    />
                  </template>
                </el-popconfirm>
              </el-tooltip>
            </div>
          </template>
        </el-table-column>
      </el-table>
    </div>

    <!-- 表单对话框 -->
    <el-dialog
      v-model="dialogVisible"
      :title="dialogTitle"
      width="500px"
      @close="resetForm"
    >
      <el-form
        ref="formRef"
        :model="formData"
        :rules="rules"
        label-width="100px"
        status-icon
      >
        <!-- 上级部门 - 不可修改 -->
        <el-form-item v-if="formData.id" label="上级部门">
          <el-input
            :value="formData.parentName || '无'"
            disabled
            placeholder="无"
          />
        </el-form-item>

        <!-- 机构编号 - 新增和编辑时都显示 -->
        <el-form-item label="编号" prop="posNumber">
          <el-input v-model="formData.posNumber" placeholder="请输入编号" />
        </el-form-item>

        <!-- 机构(type=0)显示机构名称 - 不可修改 -->
        <template v-if="formData.type === PositionType.ORGANIZATION">
          <el-form-item label="机构名称">
            <el-input
              :value="getCellNameById(formData.cellId)"
              disabled
              placeholder="请选择小区"
            />
          </el-form-item>

          <!-- 新增时显示小区选择，编辑时隐藏 -->
          <el-form-item v-if="!formData.id" label="选择小区" prop="cellId">
            <el-select
              v-model="formData.cellId"
              placeholder="请选择小区"
              style="width: 100%"
            >
              <el-option
                v-for="cell in cellList"
                :key="cell.id"
                :label="cell.name"
                :value="cell.id"
              />
            </el-select>
          </el-form-item>
        </template>

        <!-- 部门(type=1)显示部门名称 - 可修改 -->
        <template v-else>
          <el-form-item label="部门名称" prop="name">
            <el-input v-model="formData.name" placeholder="请输入部门名称" />
          </el-form-item>
        </template>

        <!-- 排序 - 可修改 -->
        <el-form-item label="排序" prop="ordered">
          <el-input-number v-model="formData.ordered" :min="0" />
        </el-form-item>
      </el-form>
      <template #footer>
        <span class="dialog-footer">
          <el-button @click="dialogVisible = false">取消</el-button>
          <el-button type="primary" @click="submitForm">确定</el-button>
        </span>
      </template>
    </el-dialog>
  </div>
</template>

<script setup lang="ts">
import { ref, reactive, onMounted, computed } from "vue";
import {
  ElMessage,
  ElMessageBox,
  type FormInstance,
  type FormRules
} from "element-plus";
import { Edit, Plus, Delete } from "@element-plus/icons-vue";
import {
  getPositionTree,
  createPosition,
  updatePosition,
  deletePosition,
  batchDeletePositions,
  getPositionById,
  type Position,
  type PositionQueryDto,
  type PositionCreateParams,
  type PositionUpdateParams,
  PositionType,
  PositionLevel
} from "@/api/position";
import { findAllCells, type Cell } from "@/api/cell";

// 搜索表单
const searchForm = reactive<PositionQueryDto>({
  posNumber: ""
});

// 机构树数据
const organizationTree = ref<Position[]>([]);

// 小区列表数据
const cellList = ref<Cell[]>([]);

// 机构选项（用于部门选择所属机构）
const organizationOptions = computed(() => {
  return organizationTree.value.filter(
    item => item.type === PositionType.ORGANIZATION
  );
});

// 选中的机构
const selectedOrganizations = ref<Position[]>([]);

// 对话框相关
const dialogVisible = ref(false);
const dialogTitle = ref("");
const formRef = ref<FormInstance>();

// 表单数据
const formData = reactive<
  PositionCreateParams & { id?: number; parentName?: string }
>({
  id: 0,
  cellId: undefined,
  posNumber: "",
  name: "",
  ordered: 0,
  parentId: undefined,
  type: PositionType.ORGANIZATION,
  // level: PositionLevel.ORGANIZATION,
  parentName: ""
});

// 表单验证规则
const rules = computed(() => ({
  posNumber: [{ required: true, message: "请输入机构编号", trigger: "blur" }],
  name:
    formData.type === PositionType.ORGANIZATION
      ? [] // 机构不需要验证name字段
      : [{ required: true, message: "请输入部门名称", trigger: "blur" }], // 部门需要验证name字段
  cellId:
    formData.type === PositionType.ORGANIZATION && !formData.id
      ? [{ required: true, message: "请选择小区", trigger: "change" }] // 新增机构时需要验证cellId字段
      : [], // 编辑机构或部门时不需要验证cellId字段
  ordered: [{ required: true, message: "请输入排序", trigger: "blur" }]
}));

// 过滤机构数据，仅显示type为0和1的数据
const filterOrganizationData = (data: Position[]): Position[] => {
  return data
    .filter(
      item =>
        item.type === PositionType.ORGANIZATION ||
        item.type === PositionType.DEPARTMENT
    )
    .map(item => {
      // 如果有子节点，递归过滤
      if (item.children && item.children.length > 0) {
        const filteredChildren = filterOrganizationData(item.children);
        return {
          ...item,
          children: filteredChildren
        };
      }
      return item;
    });
};

// 加载机构树
const loadOrganizationTree = async () => {
  try {
    const res = await getPositionTree(searchForm);
    if (res.code === 0 && res.data) {
      // 过滤仅显示type为0和1的数据
      organizationTree.value = filterOrganizationData(res.data);
    } else {
      ElMessage.error(res.message || "获取机构树失败");
    }
  } catch (error) {
    ElMessage.error("获取机构树失败");
    console.error(error);
  }
};

// 加载小区列表
const loadCellList = async () => {
  try {
    const res = await findAllCells();
    if (res.code === 0 && res.data) {
      cellList.value = res.data;
    } else {
      ElMessage.error(res.message || "获取小区列表失败");
    }
  } catch (error) {
    ElMessage.error("获取小区列表失败");
    console.error(error);
  }
};

// 根据cellId获取小区名称
const getCellNameById = (cellId: number): string => {
  const cell = cellList.value.find(item => item.id === cellId);
  return cell ? cell.name : "";
};

// 在机构树中查找指定ID的机构
const findPositionById = (id: number, tree: Position[]): Position | null => {
  for (const item of tree) {
    if (item.id === id) {
      return item;
    }
    if (item.children && item.children.length > 0) {
      const found = findPositionById(id, item.children);
      if (found) {
        return found;
      }
    }
  }
  return null;
};

// 搜索
const handleSearch = () => {
  loadOrganizationTree();
};

// 重置搜索
const resetSearch = () => {
  searchForm.posNumber = "";
  loadOrganizationTree();
};

// 新增机构
const handleAdd = () => {
  dialogTitle.value = "新增机构";
  resetForm();
  formData.type = PositionType.ORGANIZATION; // 只能添加类型为机构
  dialogVisible.value = true;
};

// 编辑机构
const handleEdit = async (row: Position) => {
  // 根据type设置对话框标题
  dialogTitle.value =
    row.type === PositionType.ORGANIZATION ? "编辑机构" : "编辑部门";
  resetForm();

  try {
    // 调用后端接口获取完整数据
    const res = await getPositionById(row.id);
    if (res.code === 0 && res.data) {
      // 将后端返回的数据赋值给表单
      Object.assign(formData, res.data);
      // 确保parentId字段正确设置
      formData.parentId = res.data.parentId;

      // 获取上级部门名称
      if (res.data.parentId) {
        const parent = findPositionById(
          res.data.parentId,
          organizationTree.value
        );
        formData.parentName = parent
          ? parent.type === PositionType.ORGANIZATION
            ? parent.cellName || parent.name
            : parent.name
          : "";
      } else {
        formData.parentName = "";
      }

      dialogVisible.value = true;
    } else {
      ElMessage.error(res.message || "获取机构详情失败");
    }
  } catch (error) {
    ElMessage.error("获取机构详情失败");
    console.error(error);
  }
};

// 删除机构
const handleDelete = async (row: Position) => {
  try {
    const res = await deletePosition(row.id);
    if (res.code === 0) {
      ElMessage.success("删除成功");
      loadOrganizationTree();
    } else {
      ElMessage.error(res.message || "删除失败");
    }
  } catch (error) {
    ElMessage.error("删除失败");
    console.error(error);
  }
};

// 表格选择变化
const handleSelectionChange = (selection: Position[]) => {
  selectedOrganizations.value = selection;
};

// 批量删除
const handleBatchDelete = () => {
  if (!selectedOrganizations.value.length) {
    ElMessage.warning("请选择要删除的机构");
    return;
  }

  ElMessageBox.confirm("确定要删除选中的机构吗？", "提示", {
    confirmButtonText: "确定",
    cancelButtonText: "取消",
    type: "warning"
  }).then(async () => {
    try {
      const ids = selectedOrganizations.value.map(item => item.id);
      const res = await batchDeletePositions(ids);
      if (res.code === 0) {
        ElMessage.success("批量删除成功");
        loadOrganizationTree();
      } else {
        ElMessage.error(res.message || "批量删除失败");
      }
    } catch (error) {
      console.error("批量删除失败:", error);
      ElMessage.error("批量删除失败");
    }
  });
};

// 重置表单
const resetForm = () => {
  // 先重置表单验证状态
  if (formRef.value) {
    formRef.value.resetFields();
  }

  // 然后重置所有数据字段
  formData.id = undefined;
  formData.cellId = undefined;
  formData.parentId = undefined;
  formData.posNumber = "";
  formData.name = "";
  formData.ordered = 0;
  formData.type = PositionType.ORGANIZATION;
  formData.parentName = "";
};

// 提交表单
const submitForm = async () => {
  if (!formRef.value) return;

  await formRef.value.validate(async (valid, fields) => {
    if (valid) {
      try {
        let res;
        if (formData.id) {
          // 更新
          const updateParams: PositionUpdateParams = {
            id: formData.id,
            posNumber: formData.posNumber,
            name:
              formData.type === PositionType.ORGANIZATION
                ? getCellNameById(formData.cellId!)
                : formData.name,
            cellId:
              formData.type === PositionType.ORGANIZATION
                ? formData.cellId
                : undefined,
            parentId:
              formData.type === PositionType.DEPARTMENT
                ? formData.parentId
                : undefined,
            type: formData.type,
            ordered: formData.ordered
          };
          res = await updatePosition(updateParams);
        } else {
          // 新增
          const createParams: PositionCreateParams = {
            posNumber: formData.posNumber,
            name:
              formData.type === PositionType.ORGANIZATION
                ? getCellNameById(formData.cellId!)
                : formData.name,
            cellId:
              formData.type === PositionType.ORGANIZATION
                ? formData.cellId
                : undefined,
            parentId:
              formData.type === PositionType.DEPARTMENT
                ? formData.parentId
                : undefined,
            type: formData.type,
            ordered: formData.ordered
          };
          res = await createPosition(createParams);
        }

        if (res.code === 0) {
          ElMessage.success(formData.id ? "更新成功" : "新增成功");
          dialogVisible.value = false;
          loadOrganizationTree();
        } else {
          ElMessage.error(
            res.message || (formData.id ? "更新失败" : "新增失败")
          );
        }
      } catch (error) {
        ElMessage.error(formData.id ? "更新失败" : "新增失败");
        console.error(error);
      }
    } else {
      console.log("表单验证失败:", fields);
    }
  });
};

// 页面加载时获取机构树和小区列表
onMounted(() => {
  loadOrganizationTree();
  loadCellList();
});
</script>

<style scoped>
.main {
  padding: 20px;
}

.operation-buttons {
  display: flex;
  gap: 8px;
  justify-content: center;
}
</style>
